
define([ 'jquery', 'knockout','text!./item.html','bootstrap', 'uui', 'director', 'grid'],
    function($, ko, template) {
        var viewModelReportItem = {
            radioDir: [{
                "value": "DR",
                "name": "借方 "
            }, {
                "value": "CR",
                "name": "贷方 "
            }],
            //1=资产、2=负债、3=净资产、4=收入、5=费用、9=其他
            combItemType: [{
                'value': "1",
                'name': "资产"
            }, {
                "value": "2",
                "name": "负债"
            }, {
                "value": "3",
                "name": "净资产"
            }, {
                "value": "4",
                "name": "收入"
            }, {
                "value": "5",
                "name": "费用"
            }, {
                "value": "9",
                "name": "其他"
            }],

            data : ko.observable({}),
            reportItemDataTable: new u.DataTable({
                params: {
                    "cls": "com.ufgov.agcfs.baseData.entity.AgcfsSysItem"
                },
                meta: {
                    'id':{},
                    'nd': {},
                    'reportItemCode': {},
                    'reportItemName': {},
                    'pitemCode': {},
                    'reportItemType': {},
                    'balDir': {},
                    'remark': {}
                }
            })
        };
        
        //查询
        viewModelReportItem.getItemData = function(){
            var queryData = {};
            var nd=$("#selectNd").val();
            queryData["search_EQ_nd"] = nd;
            viewModelReportItem.reportItemDataTable.addParams(queryData);
            app.serverEvent().addDataTable("reportItemDataTable", "all").fire({
                url: $ctx + '/evt/dispatch',
                ctrl: 'agcfs.base.agcfsItemController',
                method: 'loadItemByNd',
                success: function (data) {
                }
            });
        };

        //提交保存一个报表项
        viewModelReportItem.saveReportItemEdit = function() {
            var edit_id = $("#edit-id").val();
            var edit_nd = $("#edit-nd").val();
            var edit_reportItemCode = $("#edit-reportItemCode").val();
            var edit_reportItemName = $("#edit-reportItemName").val();
            var edit_pitemCode = $("#edit-pitemCode").val();
            var edit_reportItemType = $("#edit-reportItemType").val();
            var edit_balDir = "DR";
            if ($("#edit-balDir-CR").is(":checked")){
                edit_balDir = "CR";
            }
            var edit_remark = $("#edit-remark").val();

            $.ajax({
                url: $ctx + "/baseData/reportItem/saveReportItem",
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    id: edit_id,
                    nd: edit_nd,
                    reportItemCode: edit_reportItemCode,
                    reportItemName: edit_reportItemName,
                    pitemCode: edit_pitemCode,
                    reportItemType: edit_reportItemType,
                    balDir: edit_balDir,
                    remark: edit_remark,
                }),
                success: function (data) {
                    if (data.result == "success"){
                        var newId=data.id;
                        viewModelReportItem.getItemData();
                        viewModelReportItem.edit_notice_close();
                    }
                }
            });
        }

        viewModelReportItem.edit_notice_close = function() {
            $("#edit-nd").get(0).selectedIndex=0;
            $("#edit-reportItemCode").val("");
            $("#edit-reportItemName").val("");
            $("#edit-pitemCode").val("");

            $("#warn-text").css("display","none");
            $("#reportItem_edit-notice").modal("hide");
        }

        delReportItem = function() {
            var data = viewModelReportItem.reportItemDataTable.getCurrentRow().data;
            var delHint = "(" + data.reportItemCode.value + ")" + data.reportItemName.value;
            document.getElementById('modal-delete-text').innerHTML = "确认要删除【" + delHint + "】吗？";
            $("#delete-reportItem-notice").modal({backdrop: 'static', keyboard: false});
        }

        viewModelReportItem.delete_reportItem_close = function() {
            $("#delete-reportItem-notice").modal("hide");
        }

        //提交删除一个报表项
        viewModelReportItem.delete_reportItem = function () {
            var data = viewModelReportItem.reportItemDataTable.getCurrentRow().data;
            var id = data.id.value;
            $.ajax({
                url: $ctx + "/baseData/reportItem/deleteReportItem",
                type: "POST",
                dataType: "json",
                data: {
                    id: id
                },
                success: function (data) {
                    $("#delete-reportItem-notice").modal("hide");
                    if (data.result == "success") {
                        viewModelReportItem.getItemData();
                    } else {
                        if(data.saveError != undefined){
                            $("#error-text").text(data.saveError);
                            $("#error-notice").modal({backdrop: 'static', keyboard: false});
                        } else {
                            $("#error-text").text(data.reason);
                            $("#error-notice").modal({backdrop: 'static', keyboard: false});
                        }
                    }
                }
            });
        }

        //新增
        viewModelReportItem.addReportItem = function() {
            var nd = $("#selectNd").val();
            $("#edit-id").val("");
            $("#edit-nd").val(nd);
            $("#edit-reportItemCode").val("");
            $("#edit-reportItemName").val("");
            $("#edit-pitemCode").val("");
            $("#edit-remark").val("");

            $("#edit-reportItemCode").focus();
            $("#reportItem_edit-notice").modal({backdrop: 'static', keyboard: false});
        }

        //编辑
        viewModelReportItem.editReportItem = function(index) {
            var data = viewModelReportItem.reportItemDataTable.getCurrentRow().data;
            $("#edit-id").val(data.id.value);
            $("#edit-nd").val(data.nd.value);
            $("#edit-reportItemCode").val(data.reportItemCode.value);
            $("#edit-reportItemName").val(data.reportItemName.value);
            $("#edit-pitemCode").val(data.pitemCode.value);
            $("#edit-reportItemType").val(data.reportItemType.value);
            if (data.balDir.value=="DR"){
                $("#edit-balDir-DR").checked="checked";
            }else{
                $("#edit-balDir-CR").checked="checked";
            }
            $("#edit-remark").val(data.remark.value);

            $("#reportItem_edit-notice").modal({backdrop: 'static', keyboard: false});
        }

        //插行
        viewModelReportItem.insertOneItem=function(){
            var row = {
                "status": "new",
                "data": {
                    'id': '',
                    'nd': '',
                    'reportItemCode': '',
                    'reportItemName': '',
                    'pitemCode': '',
                    'reportItemType': '',
                    'balDir': '',
                    'remark': ''
                }
            };

            //先创建行模型，然后将数据插入行
            var r = new u.Row({
                parent: viewModelReportItem.reportItemDataTable
            });
            var id=uuid();
            row.data.id=id;
            row.data.nd=$("#selectNd").val();

            r.setData(row);
            //新增一行
            viewModelReportItem.reportItemDataTable.addRow(r);
        }

        //删行
        viewModelReportItem.deleteOneItem=function(){
            var selectedIndex=viewModelReportItem.reportItemDataTable.getSelectedIndexs();
            if (selectedIndex.length >0) {
                viewModelReportItem.reportItemDataTable.removeRow(selectedIndex[0]);
            }
        }

        //批量保存
        viewModelReportItem.saveItems = function () {
            var queryData = {};
            var nd=$("#selectNd").val();
            queryData["search_EQ_nd"] = nd;
            viewModelReportItem.reportItemDataTable.addParams(queryData);
            console.log(viewModelReportItem.reportItemDataTable);

            app.serverEvent().addDataTable("reportItemDataTable", "all").fire({
                url: $ctx + '/evt/dispatch',
                ctrl: 'agcfs.base.agcfsItemController',
                method: 'saveItemByNd',
                success: function (data) {
                    alert("保存成功");
                }
            });
        }

        //初始化年度下拉框
        viewModelReportItem.initNd = function(id) {
            var thisYear = new Date().getFullYear();
            for (var i = -5; i <= 1; i++) {
                $(id).append("<option value='" + (thisYear+i) + "'>"+(thisYear+i)+"</option>");
            }
            $(id).val(thisYear);
        }
        viewModelReportItem.initItemType = function(id) {
            var optionstring = "";
            for(var item in viewModelReportItem.combItemType)
            {
                optionstring += "<option value=\""+ viewModelReportItem.combItemType[item].value +"\" >"+ viewModelReportItem.combItemType[item].name +"</option>";
            }
            $(id).html(optionstring);
        }

        var init = function(){
            ko.cleanNode($('.content')[0]);
            app = u.createApp(
                {
                    el:'.content',
                    model: viewModelReportItem
                }
            );

            viewModelReportItem.initNd("#selectNd");
            viewModelReportItem.initNd("#edit-nd");
            viewModelReportItem.initItemType("#edit-reportItemType");
            
            //获得数据
            viewModelReportItem.getItemData();
        };

        return {
            'model' : viewModelReportItem,
            'template' : template,
            'init' : init
        };
    }

);

function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}